package com.gxgeek.eshopinventory.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gxgeek.eshopinventory.constant.RedisKeyConstant;
import com.gxgeek.eshopinventory.redis.RedisDAO;
import com.gxgeek.eshopinventory.entity.ProductInventory;
import com.gxgeek.eshopinventory.mapper.ProductInventoryMapper;
import com.gxgeek.eshopinventory.service.IProductInventoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gxgeek123
 * @since 2018-01-12
 */
@Service
public class ProductInventoryServiceImpl extends ServiceImpl<ProductInventoryMapper, ProductInventory> implements IProductInventoryService {
    @Resource
    private RedisDAO redisDAO;


    @Override
    public void updateProductInventory(ProductInventory productInventory) {
        baseMapper.updateById(productInventory);
    }

    @Override
    public void removeProductInventoryCache(ProductInventory productInventory) {
        String key = RedisKeyConstant.PRODUCTINVENTORY + productInventory.getProductId();
        redisDAO.delete(key);
    }

    @Override
    public ProductInventory findProductInventory(Integer productId) {
        return baseMapper.selectById(productId);
    }

    @Override
    public void setProductInventoryCache(ProductInventory productInventory) {
        String key = RedisKeyConstant.PRODUCTINVENTORY + productInventory.getProductId();
        redisDAO.set(key, String.valueOf(productInventory.getInventoryCnt()));

    }

    @Override
    public ProductInventory getProductInventoryCache(Integer productId) {
        String key = RedisKeyConstant.PRODUCTINVENTORY + productId;
        String inventoryCnt = redisDAO.get(key);
        if (StringUtils.isNotBlank(inventoryCnt)){
            ProductInventory productInventory = new ProductInventory();
            productInventory.setInventoryCnt(Long.valueOf(inventoryCnt));
            return productInventory;
        }

        return null;
    }

}
